var data;
$(document).ready(function() {
    $(":button").button();
    $("#dialog:ui-dialog").dialog("destroy");
    $("#mytable").dialog({
        autoOpen : false,
        height : 400,
        width : 550,
        modal : true,
        resizable : false,
        title : "设置节点审批人",
        close : function() {
        }
    });
});

$(function() {
    var WorkflowIniter = Base.extend({
        constructor:function(){
            this.initWorkflow();

            if ($.arkflow.config.editable) {
                this.initBtnSaveClick();
                this.initToolbar();
                this.initToolDrop();
                new $.arkflow.PropertyEditor({}, this.arkflowInstance);
            }
        },
        initWorkflow: function() {
            $('#arkflow').arkflow({
                flowId: 'arkflow',
                restore : "",
                restore : eval("{states : {rect1 : {type : 'start',text : {text : '开始'},attr : {x : 376,y : 28,width : 100,height : 50},props:{}},rect2 : {type : 'task',text : {text : '申请'},attr : {x : 389,y : 126,width : 100,height : 50},props:{assignee:"#{owner}",form:"sendForm.do"}},rect3 : {type : 'task',text : {text : '经理审批'},attr : {x : 389,y : 231,width : 100,height : 50},props:{assignee:"darkness",form:"manager.do"}},rect4 : {type : 'decision',text : {text : '老板审批判断'},attr : {x : 398,y : 323,width : 100,height : 50},props:{expr:"#{day > 3 ? '老板审批' : '结束'}"}},rect5 : {type : 'task',text : {text : '老板审批'},attr : {x : 609,y : 339,width : 100,height : 50},props:{form:"boss.do"}},rect6 : {type : 'end',text : {text : '结束'},attr : {x : 400,y : 442,width : 100,height : 50},props:{}}},paths : {path23 : {from : 'rect1',to : 'rect2',dots : [],text : {text : ''},textPos : {x : 0,y : -10},props : {text : {value : 'null'}}},path23 : {from : 'rect2',to : 'rect3',dots : [],text : {text : ''},textPos : {x : 0,y : -10},props : {text : {value : 'null'}}},path23 : {from : 'rect3',to : 'rect4',dots : [],text : {text : '批准'},textPos : {x : 0,y : -10},props : {text : {value : '批准'}}},path23 : {from : 'rect3',to : 'rect2',dots : [{x: 324, y: 203}],text : {text : '驳回'},textPos : {x : -18,y : -5},props : {text : {value : '驳回'}}},path23 : {from : 'rect4',to : 'rect5',dots : [],text : {text : '老板审批'},textPos : {x : 0,y : -10},props : {text : {value : '老板审批'}}},path23 : {from : 'rect4',to : 'rect6',dots : [],text : {text : '结束'},textPos : {x : 0,y : -10},props : {text : {value : '结束'}}},path23 : {from : 'rect5',to : 'rect6',dots : [],text : {text : ''},textPos : {x : -7,y : -19},props : {text : {value : 'null'}}}},props : {props : {name : {value : 'yj'},key : {value : ''},desc : {value : ''}}}}"),
                		//"({states:{rect13:{type:'start',text:{text:'开始'}, attr:{ x:376, y:28, width:100, height:50}, props:{text:{value:'开始'},temp1:{value:''},temp2:{value:''}}},rect14:{type:'task',text:{text:'申请'}, attr:{ x:389, y:126, width:100, height:50}, props:{text:{value:'申请'},temp1:{value:''},temp2:{value:''}}},rect15:{type:'task',text:{text:'经理审批'}, attr:{ x:389, y:231, width:100, height:50}, props:{text:{value:'经理审批'},temp1:{value:''},temp2:{value:''}}},rect16:{type:'decision',text:{text:'老板审批判断'}, attr:{ x:398, y:323, width:100, height:50}, props:{text:{value:'老板审批判断'},temp1:{value:''},temp2:{value:''}}},rect17:{type:'task',text:{text:'老板审批'}, attr:{ x:609, y:339, width:100, height:50}, props:{text:{value:'老板审批'},temp1:{value:''},temp2:{value:''}}},rect18:{type:'end',text:{text:'结束'}, attr:{ x:400, y:442, width:100, height:50}, props:{text:{value:'结束'},temp1:{value:''},temp2:{value:''}}}},paths:{path19:{from:'rect13',to:'rect14', dots:[],text:{text:'TO 任务'},textPos:{x:0,y:-10}, props:{text:{value:''}}},path20:{from:'rect14',to:'rect15', dots:[],text:{text:''},textPos:{x:0,y:-10}, props:{text:{value:''}}},path21:{from:'rect15',to:'rect16', dots:[],text:{text:'批准'},textPos:{x:0,y:-10}, props:{text:{value:'批准'}}},path23:{from:'rect15',to:'rect14', dots:[{x:324,y:203}],text:{text:'驳回'},textPos:{x:-18,y:-5}, props:{text:{value:'驳回'}}},path25:{from:'rect16',to:'rect17', dots:[],text:{text:'老板审批'},textPos:{x:0,y:-10}, props:{text:{value:'老板审批'}}},path26:{from:'rect17',to:'rect18', dots:[],text:{text:''},textPos:{x:-7,y:-19}, props:{text:{value:''}}},path27:{from:'rect16',to:'rect18', dots:[],text:{text:'结束'},textPos:{x:0,y:-10}, props:{text:{value:'结束'}}}},props:{props:{name:{value:'yj'},key:{value:''},desc:{value:''}}}})"),
                // basePath : "",
                tools : {
                    save : {
                        onclick : function(data) {
                            $.ajax({
                                type : "POST",
                                url : "workflowAjax!editWorkflow.action?isEdit=0&workflowData=" + data,
                                dataType : "json",
                                error : function(XMLHttpRequest, textStatus, errorThrown) {
                                    var data = XMLHttpRequest.responseText;
                                    alert(data);
                                },
                                success : function(data, textStatus) {
                                    var json = eval(data);
                                    if (json.f == 's') {
                                        $("#data").val(json.workflowData);
                                        deleteRows();

                                        var option = "";
                                        for ( j = 0; j < json.roleList.length; j++) {
                                            option += "<option value='" + json.roleList[j].roleId + "'>" + json.roleList[j].roleName + "</option>";
                                        }

                                        var fromTable = document.getElementById("flowForm");
                                        var decisionTable = document.getElementById("flowDecision");
                                        var formCount = 0;
                                        var decisionCount = 0;

                                        for ( i = 0; i < json.flowList.length; i++) {
                                            if (json.flowList[i].type == "decision") {
                                                decisionCount++;
                                                var row = decisionTable.insertRow(decisionCount);
                                                var col = row.insertCell(0);
                                                col.innerHTML = json.flowList[i].name;
                                                col = row.insertCell(1);
                                                var html = "<input type=\"text\" name=\"flowList[" + i + "].expr\" value='" + json.flowList[i].expr + "' style=\"width: 350px\"/>";
                                                html = html + "<input type=\"hidden\" name=\"flowList[" + i + "].name\" value='" + json.flowList[i].name + "'/>";
                                                col.innerHTML = html;
                                            } else {
                                                formCount++;
                                                var row = fromTable.insertRow(formCount);
                                                var col = row.insertCell(0);
                                                col.innerHTML = json.flowList[i].name;
                                                col = row.insertCell(1);
                                                var html = "<input type='text' name='flowList[" + i + "].form' value='" + json.flowList[i].form + "'/>";
                                                html = html + "<input type=\"hidden\" name=\"flowList[" + i + "].name\" value='" + json.flowList[i].name + "'/>";
                                                html = html + "<input type=\"hidden\" value='flowList[" + i + "].assignType'/>";
                                                col.innerHTML = html;
                                                col = row.insertCell(2);
                                                var htm = "<input name=\"flowList[" + i + "].assignType\" type=\"radio\" value=\"0\" onclick=\"show(" + i + ",2)\"/>角色";
                                                htm = htm + "<input name=\"flowList[" + i + "].assignType\" type=\"radio\"  value=\"1\" onclick=\"show(" + i + ",3)\" checked=\"checked\"/>用户";
                                                htm = htm + "<input name=\"flowList[" + i + "].assignType\" type=\"radio\"  value=\"2\" onclick=\"show(" + i + ",4)\"/>发起人";
                                                col.innerHTML = htm;
                                                col = row.insertCell(3);
                                                var Inputhtm = "<select style=\"display:none;width:100px;\" id =\"" + i + "j\" name=\"flowList[" + i + "].assignValue\">" + option + "</select>";
                                                Inputhtm = Inputhtm + "<input id =\"" + i + "y\" style=\"width:100px;\"  type=\"text\"  name=\"flowList[" + i + "].assignee\" value='" + json.flowList[i].assignee + "'/>";
                                                col.innerHTML = Inputhtm;
                                            }
                                        }
                                        if (decisionCount > 0) {
                                            $("#flowDecision").attr("style", "display:inline");
                                        } else {
                                            $("#flowDecision").attr("style", "display:none");
                                        }
                                        $("#mytable").dialog("open");
                                    } else {
                                        alert(json.m);
                                    }
                                }
                            });
                        }
                    }
                }
            });
            this.arkflowInstance = $.arkflow.ArkFlow.findFlow('arkflow');
        },
        initBtnSaveClick: function() {
            var arkflowInstance = this.arkflowInstance;
                //保存事件,封装图形JSON数据
            $("#arkflow_save").click(function() {

                var flowDefine = arkflowInstance.toDefineJson();
                var flowValidInfo = arkflowInstance.validateDefine(flowDefine);
                if(flowValidInfo.success) {
                    $.arkflow.config.tools.save.onclick(flowDefine);
                } else {
                    alert(flowValidInfo.msg);
                }
            });
        },
        initToolbar: function() {
            var arkflowInstance = this.arkflowInstance;
            $("#arkflow_tools").draggable({
                handle : "#arkflow_tools_handle"
            }).css($.arkflow.config.tools.attr);
            $("#arkflow_tools .node").hover(function() {
                $(this).addClass("mover");
            }, function() {
                $(this).removeClass("mover");
            });
            $("#arkflow_tools .selectable").click(function() {
                $(".selected").removeClass("selected");
                $(this).addClass("selected");
                arkflowInstance.setMod(this.id);
            });
            $("#arkflow_tools .state").each(function() {
                $(this).draggable({
                    helper : "clone"
                });
            });
        },
        initToolDrop:function() {
            var arkflowInstance = this.arkflowInstance;
            //拖动添加矩形
            $('#arkflow').droppable({
                accept : ".state",
                drop : function(event, currNode) {
                    console.log('drop state');
                    arkflowInstance.addFlowNode(currNode.helper.attr("type"), currNode.helper.offset().left, currNode.helper.offset().top);
                }
            });
        }
    });

    new WorkflowIniter();
});

function show(i, flag) {
    var num = i + 1;
    // i:radioId,num:selectID和inputID
    // flag:2,角色;3,用户
    if (flag == 2) {
        // 下拉宽显示
        document.getElementById(i + "j").style.display = "block";
        document.getElementById(i + "y").style.display = "none";
    } else if (flag == 3) {
        document.getElementById(i + "y").style.display = "block";
        document.getElementById(i + "j").style.display = "none";
    } else if (flag == 4) {
        document.getElementById(i + "y").style.display = "none";
        document.getElementById(i + "j").style.display = "none";
    }
}

function deleteRows() {
    var oTable = document.getElementById("flowForm");
    // 源
    for (var i = oTable.rows.length; i > 1; i--) {
        oTable.deleteRow(1);
    }

    var flowDecisionTable = document.getElementById("flowDecision");
    // 源
    for (var i = flowDecisionTable.rows.length; i > 1; i--) {
        flowDecisionTable.deleteRow(1);
    }
}

function getRadioValue(radioName) {
    var radios = document.getElementsByName(radioName);
    if (!radios)
        return '';
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked)
            return radios[i].value;
    }
    return '';
}

function checkAndDataHandle() {
    // 根据执行内容，验证table内容是否为空，用于向后台提交
    var oTable = document.getElementById("flowForm");
    // 源
    var bTable = document.getElementById("flowDecision");
    var msg = "";
    for (var i = 1; i < oTable.rows.length; i++) {
        var form = oTable.rows[i].cells[1].childNodes[0].value;
        var nodeName = oTable.rows[i].cells[1].childNodes[1].value;
        var assigneeTypeName = oTable.rows[i].cells[1].childNodes[2].value;
        var assigneeType = getRadioValue(assigneeTypeName);

        var assignee = oTable.rows[i].cells[3].childNodes[1].value;
        if (assigneeType == '0') {
            assignee = oTable.rows[i].cells[3].childNodes[0].value;
        }
        if (form == null || form == "") {
            msg += "第" + i + "行,节点：【" + nodeName + "】的【页面内容】不可为空" + "\n";
        }
        if (assigneeType != '2') {
            if (assignee == null || assignee == "") {
                msg += "第" + i + "行,节点：【" + nodeName + "】的【审批人】不可为空" + "\n";
            }
        }
    }
    for (var i = 1; i < bTable.rows.length; i++) {
        var nodeName = bTable.rows[i].cells[1].childNodes[1].value;
        var epr = bTable.rows[i].cells[1].childNodes[0].value;
        if (epr == null || epr == "") {
            msg += "第" + i + "行,节点：【" + nodeName + "】的条件值不可为空" + "\n";
        }
    }
    return msg;
}

function save() {
    var msg = checkAndDataHandle();
    if (msg != "") {
        alert(msg);
        return false;
    }
    // alert(decodeURIComponent($("#form").serialize(),true));

    $.ajax({
        type : "POST",
        url : "workflowAjax!saveFlow.action?workflowData=" + $("#data").val(),
        data : $("#form").serialize(),
        dataType : "json",
        error : function() {
        },
        success : function(data, textStatus) {
            var json = eval(data);
            if (json.f = 's') {
                alert("保存成功");
                $("#mytable").dialog("close");
                this.location.href = "workflow!initAddWorkFlowPage.do";
            } else {
                alert("保存失败:" + json.m);
            }
        }
    });
}
